package com.keyi.ddns.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.dnspod.v20210323.DnspodClient;
import com.tencentcloudapi.dnspod.v20210323.models.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
@EnableScheduling
public class DDns {
    @Value("${domain-name}")
    public String domainName;
    @Value("${sub-domain-name}")
    public String subDomainName;
    @Value("${record-id}")
    public String recordId;
    @Value("${secret-id}")
    public String secretId;
    @Value("${secret-key}")
    public String secretKey;
    //创建一个每5分钟执行的任务，可自行调整频率
    @Scheduled( fixedRate = 5*60*1000)
    public void scheduledTask() {
        String fullDomainName = subDomainName + "." + domainName;
        long recordIdL = Long.parseLong(recordId);
        String ipByDomainIp = getIpByDomainIp(fullDomainName);
        String ipByThird = getIpV4();
        if (ipByDomainIp.equals(ipByThird)) {
            System.out.println("IP地址相同，无需更新");
        } else {
            System.out.println("IP地址不相同，更新:" + ipByThird);
            refreshDns(domainName, subDomainName, recordIdL, ipByThird);
        }
    }

    public String refreshDns(String domainName, String subDomainName, long recordId, String clientPublicIp) {
        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("dnspod.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            DnspodClient client = new DnspodClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            ModifyRecordRequest req = new ModifyRecordRequest();
            req.setDomain(domainName);
            req.setSubDomain(subDomainName);
            req.setRecordType("A");
            req.setRecordLine("默认");
            //如果不传ip，获取本机的公网ipv4地址
            if (StrUtil.isNotEmpty(clientPublicIp))
                req.setValue(clientPublicIp);
            else
                req.setValue(getIpV4());
            //recordId的获取可前往：https://console.cloud.tencent.com/api/explorer?Product=dnspod&Version=2021-03-23&Action=DescribeRecord
            req.setRecordId(recordId);
            // 返回的resp是一个ModifyRecordResponse的实例，与请求对象对应
            ModifyRecordResponse resp = client.ModifyRecord(req);
            // 输出json格式的字符串回包
//            Console.log(ModifyRecordResponse.toJsonString(resp));
            return ModifyRecordResponse.toJsonString(resp);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getIpV4(){
        String ipV4 = "";
        try{
            String ipStr = HttpUtil.get("https://www.taobao.com/help/getip.php");
            ipV4 = ipStr.split("\"")[1];
        }catch(Exception e){
            e.printStackTrace();
            ipV4 = "127.0.0.1";
        }
        return ipV4;

    }

    public static String getIpByDomainIp(String domain){
        InetAddress[] addresses = new InetAddress[0];
        try {
            addresses = InetAddress.getAllByName(domain);
        } catch (UnknownHostException e) {
            return "";
        }
        return addresses[0].getHostAddress();
    }

}
